import React, { useState, createContext } from 'react'
import { signal, effect, useSignal, useComputed } from "@preact/signals-react";


// https://www.npmjs.com/package/@preact/signals-react
// https://www.bilibili.com/video/BV1ye411Q7MN/


const name = signal('Echo')

setInterval(() => {
  name.value = Math.random()
}, 1000);




// Unoptimized: Will trigger the surrounding
// component to re-render
const NameLabel = () => {
  console.log('NameLabel render...');

  return (
    <p>
      Show Value: {name.value}
    </p>
  )
}


// Optimized: Will update the text node directly
const NameLabel2 = () => {
  console.log('NameLabel2 render...');

  return (
    <p>
      Show: {name}
    </p>
  )
}


// Hooks
// If you need to instantiate new signals inside your components, you can use the useSignal or useComputed hook.
const Counter = () => {
  const count = useSignal(0)
  const double = useComputed(() => count.value * 2)


  console.log('Counter render...')
  return (
    <button onClick={() => count.value++}>
      {/* Value: {count.value}, value x 2 = {double.value} */}
      Value: {count}, value x 2 = {double}
    </button>
  )
}



const getTodos = () => {
  const value = localStorage.getItem("Todos")
  if(!value) {
    return []
  }
  
  return JSON.parse(value)
}

// 定义signal对象
const todos = signal(getTodos())

// 可以导出给其他组件使用
// export const todos = signal(getTodos())

// todos.value有任何的变化，都会执行回调
effect(() => {
  localStorage.setItem("Todos", JSON.stringify(todos.value))
})



const TodosList = () => {
  const [todoName, setTodoName] = useState("")


  const addTodo = (e) => {
    e.preventDefault()

    todos.value = [
      ...todos.value,
      { id: Math.random(), name: todoName, completed: false }
    ]


    setTodoName(null)
  }


  const toggleTodo = (id, completed) => {
    todos.value = todos.value.map(todo => {
      if (id === todo.id) {
        return { ...todo, completed }
      }

      return todo
    })
  }

  console.log('TodoList render...')
  return (
    <div>
      <h1>Todos</h1>

      <form onSubmit={addTodo} className=''>
        <label>New Todo</label>
        <input
          type='text'
          value={todoName}
          onChange={e => setTodoName(e.target.value)}
        />
        <button>Add</button>
      </form>

      <ul>
        {
          todos.value.map(todo => {
            return (
              <li key={todo.id}>
                <label>
                  <input
                    type='checkbox'
                    checked={todo.completed}
                    onChange={e => toggleTodo(todo.id, e.target.checked)}
                  />
                  {todo.name}
                </label>
              </li>
            )
          })
        }
      </ul>
    </div>
  )
}



function SignalApp() {
  console.log('SignalApp render...');


  return (
    <React.StrictMode>
      <div>
        {/* <Counter />
        <NameLabel />
        <NameLabel2 /> */}

        <TodosList />
      </div>
    </React.StrictMode>
  )
}

export default SignalApp
